//
//  ShiPingViewController.m
//  ProJectB_1
//
//  Created by lanou3g on 16/8/12.
//  Copyright © 2016年 yangshukai. All rights reserved.
//

#warning 视频1

#import "ShiPingViewController.h"
#import "ShiPinModelU.h"
#import "AFNetworking.h"
#import "MJRefresh.h"

#import "shiPinTableViewCell.h"
#import "WMPlayer.h"
#import <ImageIO/ImageIO.h>

#define kScreenWidth  [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
#define kDeviceVersion [[UIDevice currentDevice].systemVersion floatValue]
#define WS(weakSelf) __weak __typeof(&*self)weakSelf = self;

#define kNavbarHeight ((kDeviceVersion>=7.0)? 64 :44 )
#define kIOS7DELTA   ((kDeviceVersion>=7.0)? 20 :0 )
#define kTabBarHeight 49

typedef enum{
    MYTopicTypeAll =1,
    MYTopicTypePicture =10,
    MYTopicTypeWord =29,
    MYTopicTypeVideo =41,
    MYTopicTyperideo =31
}MYTopicType;

@interface ShiPingViewController ()<UITableViewDataSource, UITableViewDelegate, WMPlayerDelegate, UIScrollViewDelegate>

{
    BOOL isSmallScreen;
    WMPlayer *wmPlayer;
    NSIndexPath *currentIndexPath;
}


@property (nonatomic,strong) UITableView *shipinTableView;

@property (nonatomic,strong) ShiPinModelU *shiPinModelU;

@property (nonatomic,strong) NSMutableArray *dataArray;

@property (nonatomic,assign) MYTopicType type;

@property (nonatomic,strong) NSMutableDictionary *params;

@property (nonatomic,strong) NSString *maxtime;
//当前页码
@property (nonatomic,assign)NSInteger page;

@property (nonatomic,strong) shiPinTableViewCell *shiPinCell;

@property (nonatomic,strong) NSMutableArray *imageSizeArray;

@end

@implementation ShiPingViewController

- (NSMutableArray *)imageSizeArray {
    if (_imageSizeArray == nil) {
        _imageSizeArray = [NSMutableArray array];
    }
    return _imageSizeArray;
}

- (NSMutableArray *)dataArray {
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.type = 41;
    
    
    [self viewLoad];
    
    [self setUpRefresh];

    
    
    
}

- (void)viewLoad {
    _shipinTableView = [[UITableView alloc]initWithFrame:[UIScreen mainScreen].bounds style:(UITableViewStylePlain)];
    [_shipinTableView registerClass:[shiPinTableViewCell class] forCellReuseIdentifier:@"shipinTableViewCell"];
    _shipinTableView.delegate = self;
    _shipinTableView.dataSource = self;
    [self.view addSubview:self.shipinTableView];

    CGFloat top = [UIScreen mainScreen].bounds.size.height / 100 * 3;
    CGFloat botton = [UIScreen mainScreen].bounds.size.height / 100 * 3;
    self.shipinTableView.contentInset = UIEdgeInsetsMake(top, 0, botton, 0);
//    设置滚动条的内边距
    self.shipinTableView.scrollIndicatorInsets = self.shipinTableView.contentInset;
    
    self.shipinTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.shipinTableView.backgroundColor = [UIColor clearColor];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"退出" style:(UIBarButtonItemStylePlain) target:self action:@selector(Menu:)];
}

- (void)Menu:(UIBarButtonItem *)sender{
    NSLog(@"退出视频");
    DrawerViewController *menuController = (DrawerViewController*)((AppDelegate *)[[UIApplication sharedApplication] delegate]).rootTabBarViewController.drawerController;
    [menuController dismissViewControllerAnimated:YES completion:nil];
}



#pragma mark ---上下
- (void)setUpRefresh {
    // 下拉刷新
    self.shipinTableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewTopics)];
    // 自动改变透明度
    self.shipinTableView.header.automaticallyChangeAlpha = YES;
    // 一进界面就刷新
    [self.shipinTableView.header beginRefreshing];
    
    // 上拉刷新
    self.shipinTableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreTopics)];
}

#pragma mark ---获取数据
- (void)loadNewTopics {
    [self.shipinTableView.footer endRefreshing];
    //发送请求给服务器,参数
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    params[@"a"] =@"list";
    params[@"c"] =@"data";
    params[@"type"] = @(self.type);
    self.params = params;
    
    __weak typeof(self)weakSelf = self;
    //发送请求
    [[AFHTTPSessionManager manager]GET:@"http://api.budejie.com/api/api_open.php" parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        
        NSLog(@"%@", responseObject);
        
        if (weakSelf.params != params) {
            [weakSelf.shipinTableView.header endRefreshing];
            return ;
        }
        [weakSelf.dataArray removeAllObjects];
        weakSelf.page = 0;
        weakSelf.maxtime = responseObject[@"info"][@"maxtime"];
        
        NSArray *allArray = responseObject[@"list"];
        for (NSDictionary *diction in allArray) {
            NSMutableArray *imageSizeArr = [NSMutableArray array];
            ShiPinModelU *model = [[ShiPinModelU alloc]init];
            [model setValuesForKeysWithDictionary:diction];
            [weakSelf.dataArray addObject:model];
            CGSize size = [weakSelf getImageSizeWithURL:model.image1];
            NSString *imageWidth = [NSString stringWithFormat:@"%f", size.width];
            NSString *imageHeight = [NSString stringWithFormat:@"%f", size.height];
            [imageSizeArr addObject:imageWidth];
            [imageSizeArr addObject:imageHeight];
            [weakSelf.imageSizeArray addObject:imageSizeArr];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.shipinTableView reloadData];
            
            [weakSelf.shipinTableView.header endRefreshing];
            weakSelf.page = 0;
        });
#warning 获取图片的size
//        for (ShiPinModelU *model in weakSelf.dataArray) {
//            CGSize size = [weakSelf getImageSizeWithURL:model.image1];
//            [weakSelf.imageSizeArray addObject:size];
//        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //上一次请求参数(用于处理最后一次网络请求)
        if (weakSelf.params !=params) return ;
        //结束刷新
        [weakSelf.shipinTableView.header endRefreshing];
    }];
}

#pragma mark--- 获取更多
- (void)loadMoreTopics {
    [self.shipinTableView.header endRefreshing];
    self.page ++;
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    params[@"a"] =@"list";
    params[@"c"] =@"data";
    params[@"type"] = @(self.type);
    params[@"page"] =@(self.page);
    params[@"maxtime"] =self.maxtime;
    self.params = params;
    __weak typeof(self) weakSelf = self;
    //发送请求
    [[AFHTTPSessionManager manager]GET:@"http://api.budejie.com/api/api_open.php" parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
                                
        NSLog(@"%@", responseObject);
        
        //上一次请求参数(用于处理最后一次网络请求)
        if (weakSelf.params !=params) return ;
        
        //存储maxtime(每次返回数据都会有maxtime)
        weakSelf.maxtime =responseObject[@"info"][@"maxtime"];
        
        NSArray *allArray = responseObject[@"list"];
        for (NSDictionary *diction in allArray) {
            ShiPinModelU *model = [[ShiPinModelU alloc]init];
            [model setValuesForKeysWithDictionary:diction];
            [weakSelf.dataArray addObject:model];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            //刷新表格
            [weakSelf.shipinTableView reloadData];
            //结束刷新
            [weakSelf.shipinTableView.footer endRefreshing];
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //上一次请求参数(用于处理最后一次网络请求)
        if (weakSelf.params !=params) return ;
        
        //结束刷新
        [weakSelf.shipinTableView.footer endRefreshing];
        //恢复页码
        weakSelf.page --;

    }];
}





- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    
    shiPinTableViewCell *cell = [self.shipinTableView dequeueReusableCellWithIdentifier:@"shipinTableViewCell" forIndexPath:indexPath];
    
    ShiPinModelU *shiPin = self.dataArray[indexPath.section];
    cell.shiPinModelU = shiPin;
    [cell.playButton addTarget:self action:@selector(startPlayVideo:) forControlEvents:UIControlEventTouchUpInside];
    cell.playButton.tag = indexPath.section;
    
    if (wmPlayer&&wmPlayer.superview) {
        if (indexPath.section == currentIndexPath.section) {
            [cell.playButton.superview sendSubviewToBack:cell.playButton];
        }else{
            [cell.playButton.superview bringSubviewToFront:cell.playButton];
        }
        NSArray *indexpaths = [tableView indexPathsForVisibleRows];
        if (![indexpaths containsObject:currentIndexPath]&&currentIndexPath!=nil) {//复用
            
            if ([[UIApplication sharedApplication].keyWindow.subviews containsObject:wmPlayer]) {
                wmPlayer.hidden = NO;
            }else{
                wmPlayer.hidden = YES;
                [cell.playButton.superview bringSubviewToFront:cell.playButton];
            }
        }else{
            if ([cell.image1.subviews containsObject:wmPlayer]) {
                [cell.image1 addSubview:wmPlayer];
                
                [wmPlayer play];
                wmPlayer.hidden = NO;
            }
            
        }
    }
    
    
    
    cell.backgroundColor = [UIColor whiteColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    cell.backgroundColor = [UIColor whiteColor];
    
    return cell;
    
    
}

- (void)startPlayVideo:(UIButton *)sender{
    shiPinTableViewCell *cell = [self.shipinTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:sender.tag]];
    cell.playTime.alpha = 0;
    cell.videoTimeLable.alpha = 0;
    cell.playButton.frame = CGRectMake(0, 0, 0, 0);
    currentIndexPath = [NSIndexPath indexPathForRow:0 inSection:sender.tag];
    if ([UIDevice currentDevice].systemVersion.floatValue>=8||[UIDevice currentDevice].systemVersion.floatValue<7) {
        NSLog(@"---%@", (shiPinTableViewCell *)sender.superview.superview);
        self.shiPinCell = (shiPinTableViewCell *)sender.superview.superview;
        
    }else{//ios7系统 UITableViewCell上多了一个层级UITableViewCellScrollView
        self.shiPinCell = (shiPinTableViewCell *)sender.superview.superview.subviews;
        
    }
    ShiPinModelU *model = [self.dataArray objectAtIndex:sender.tag];
    if (wmPlayer) {
        [self releaseWMPlayer];
        wmPlayer = [[WMPlayer alloc]initWithFrame:self.shiPinCell.image1.bounds];
        wmPlayer.delegate = self;
        wmPlayer.closeBtnStyle = CloseBtnStyleClose;
        wmPlayer.URLString = model.videouri;
        
    }else{
//        abort();
#warning 更改frame
        wmPlayer = [[WMPlayer alloc]initWithFrame:self.shiPinCell.image1.bounds];
        wmPlayer.delegate = self;
        wmPlayer.closeBtnStyle = CloseBtnStyleClose;
        wmPlayer.URLString = model.videouri;
    }
    [self.shiPinCell.image1 addSubview:wmPlayer];
    [self.shiPinCell.image1 bringSubviewToFront:wmPlayer];
    [self.shiPinCell.playButton.superview sendSubviewToBack:self.shiPinCell.playButton];
    [self.shipinTableView reloadData];
    
}

#pragma mark scrollView delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if(scrollView ==self.shipinTableView){
        if (wmPlayer==nil) {
            return;
        }
        
        if (wmPlayer.superview) {
            CGRect rectInTableView = [self.shipinTableView rectForRowAtIndexPath:currentIndexPath];
            CGRect rectInSuperview = [self.shipinTableView convertRect:rectInTableView toView:[self.shipinTableView superview]];
            if (rectInSuperview.origin.y<-self.shiPinCell.image1.frame.size.height||rectInSuperview.origin.y>kScreenHeight-kNavbarHeight-kTabBarHeight) {//往上拖动
                
                if ([[UIApplication sharedApplication].keyWindow.subviews containsObject:wmPlayer]&&isSmallScreen) {
                    isSmallScreen = YES;
                }else{
                    //放widow上,小屏显示
                    [self toSmallScreen];
                }
                
            }else{
                if ([self.shiPinCell.image1.subviews containsObject:wmPlayer]) {
                    
                }else{
                    [self toCell];
                }
            }
        }
        
    }
}

-(void)toCell{
    shiPinTableViewCell *currentCell = (shiPinTableViewCell *)[self.shipinTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:currentIndexPath.row inSection:0]];
    __weak typeof(self) weakSelf = self;
    [wmPlayer removeFromSuperview];
    NSLog(@"row = %ld",currentIndexPath.row);
    
    
    // 取出图片的尺寸
    
    
    
    [UIView animateWithDuration:0.5f animations:^{
        wmPlayer.transform = CGAffineTransformIdentity;
        
        
        
//        wmPlayer.frame = currentCell.image1.bounds;
        [wmPlayer mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(currentCell.mas_left).offset(10);
            make.top.equalTo(currentCell.text.mas_bottom).offset(10);
            make.right.equalTo(currentCell.mas_right).offset(-10);
            make.height.offset(((weakSelf.shipinTableView.frame.size.width - 20) / 5 * 3));
        }];
        
        
        
        
        
        
        
        
        
        
        wmPlayer.playerLayer.frame =  wmPlayer.bounds;
        [currentCell.image1 addSubview:wmPlayer];
        [currentCell.image1 bringSubviewToFront:wmPlayer];
        [wmPlayer.bottomView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(wmPlayer).with.offset(0);
            make.right.equalTo(wmPlayer).with.offset(0);
            make.height.mas_equalTo(40);
            make.bottom.equalTo(wmPlayer).with.offset(0);
        }];
        [wmPlayer.topView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(wmPlayer).with.offset(0);
            make.right.equalTo(wmPlayer).with.offset(0);
            make.height.mas_equalTo(40);
            make.top.equalTo(wmPlayer).with.offset(0);
        }];
        [wmPlayer.titleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(wmPlayer.topView).with.offset(45);
            make.right.equalTo(wmPlayer.topView).with.offset(-45);
            make.center.equalTo(wmPlayer.topView);
            make.top.equalTo(wmPlayer.topView).with.offset(0);
        }];
        [wmPlayer.closeBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(wmPlayer).with.offset(5);
            make.height.mas_equalTo(30);
            make.width.mas_equalTo(30);
            make.top.equalTo(wmPlayer).with.offset(5);
        }];
        [wmPlayer.loadFailedLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(wmPlayer);
            make.width.equalTo(wmPlayer);
            make.height.equalTo(@30);
        }];
    }completion:^(BOOL finished) {
        wmPlayer.isFullscreen = NO;
        [self setNeedsStatusBarAppearanceUpdate];
        isSmallScreen = NO;
        wmPlayer.fullScreenBtn.selected = NO;
        currentCell.playTime.alpha = 0;
    }];
    
}

-(void)toSmallScreen{
    //放widow上
    
    __weak typeof(self) weakSelf = self;
    
    [wmPlayer removeFromSuperview];
    [UIView animateWithDuration:0.5f animations:^{
        wmPlayer.transform = CGAffineTransformIdentity;
        wmPlayer.frame = CGRectMake(kScreenWidth/2,kScreenHeight-kTabBarHeight-(kScreenWidth/2)*0.75, kScreenWidth/2, (kScreenWidth/2)*0.75);
        wmPlayer.playerLayer.frame =  wmPlayer.bounds;
        [[UIApplication sharedApplication].keyWindow addSubview:wmPlayer];
        [wmPlayer.bottomView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(wmPlayer).with.offset(0);
            make.right.equalTo(wmPlayer).with.offset(0);
            make.height.mas_equalTo(40);
            make.bottom.equalTo(wmPlayer).with.offset(0);
        }];
        [wmPlayer.topView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(wmPlayer).with.offset(0);
            make.right.equalTo(wmPlayer).with.offset(0);
            make.height.mas_equalTo(40);
            make.top.equalTo(wmPlayer).with.offset(0);
        }];
        [wmPlayer.titleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(wmPlayer.topView).with.offset(45);
            make.right.equalTo(wmPlayer.topView).with.offset(-45);
            make.center.equalTo(wmPlayer.topView);
            make.top.equalTo(wmPlayer.topView).with.offset(0);
        }];
        [wmPlayer.closeBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(wmPlayer).with.offset(5);
            make.height.mas_equalTo(30);
            make.width.mas_equalTo(30);
            make.top.equalTo(wmPlayer).with.offset(5);
            
        }];
        [wmPlayer.loadFailedLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(wmPlayer);
            make.width.equalTo(wmPlayer);
            make.height.equalTo(@30);
        }];
        
    }completion:^(BOOL finished) {
        wmPlayer.isFullscreen = NO;
        [self setNeedsStatusBarAppearanceUpdate];
        wmPlayer.fullScreenBtn.selected = NO;
        isSmallScreen = YES;
        [[UIApplication sharedApplication].keyWindow bringSubviewToFront:wmPlayer];
        [weakSelf.shipinTableView reloadData];
    }];
    
}


-(void)releaseWMPlayer{
    [wmPlayer.player.currentItem cancelPendingSeeks];
    [wmPlayer.player.currentItem.asset cancelLoading];
    [wmPlayer pause];
    
    
    [wmPlayer removeFromSuperview];
    [wmPlayer.playerLayer removeFromSuperlayer];
    [wmPlayer.player replaceCurrentItemWithPlayerItem:nil];
    wmPlayer.player = nil;
    wmPlayer.currentItem = nil;
    //释放定时器，否侧不会调用WMPlayer中的dealloc方法
    [wmPlayer.autoDismissTimer invalidate];
    wmPlayer.autoDismissTimer = nil;
    
    
    wmPlayer.playOrPauseBtn = nil;
    wmPlayer.playerLayer = nil;
    wmPlayer = nil;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:14]};
    
    ShiPinModelU *model = self.dataArray[indexPath.section];
    NSString *text = model.text;
    
    CGSize retSize = [text boundingRectWithSize:CGSizeMake(self.view.bounds.size.width - 20, 10000000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attribute context:nil].size;
    
    NSMutableArray *imageSizeArr = self.imageSizeArray[indexPath.section];
    CGSize imageSize = CGSizeMake([imageSizeArr[0] floatValue], [imageSizeArr[1] floatValue]);
    CGFloat make = 0.0;
    
    if (((imageSize.width > [UIScreen mainScreen].bounds.size.width - 20) && (imageSize.height > ((self.shipinTableView.frame.size.width - 20) / 5 * 3)))) {
        if (imageSize.width / imageSize.height > ([UIScreen mainScreen].bounds.size.width - 20) / ((self.shipinTableView.frame.size.width - 20) / 5 * 3)) {
            // 比较宽
//            make.width.offset([UIScreen mainScreen].bounds.size.width - 20);
            make = imageSize.height;
        } else {
            // 比较高
            make = ((self.shipinTableView.frame.size.width - 20) / 5 * 3);
//            make.width.offset(imageSize.width);
        }
    } else if (imageSize.width > [UIScreen mainScreen].bounds.size.width - 20) {
//        make.width.offset([UIScreen mainScreen].bounds.size.width - 20);
        make = ([UIScreen mainScreen].bounds.size.width - 20)*(imageSize.height)/(imageSize.width);
        
    } else if (imageSize.height > ((self.shipinTableView.frame.size.width - 20) / 5 * 3)) {
        make = ((self.shipinTableView.frame.size.width - 20) / 5 * 3);
//        make.width.offset((imageSize.width)*((self.shipinTableView.frame.size.width - 20) / 5 * 3)/(imageSize.height));
    }
    NSLog(@"%f", make);
    
    
    
    
    return retSize.height + 4 + 20 + 5 + 10 + 10 + ([UIScreen mainScreen].bounds.size.width - 20) / 5 * 3 + 10 + 40 + [UIScreen mainScreen].bounds.size.width / 100 * 10;
//    return retSize.height + 4 + 40 + 10 + 10 + make + 10 + self.shipinTableView.frame.size.width / 100 * 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footer = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 10)];
    footer.backgroundColor = [UIColor lightGrayColor];
    return footer;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}







// 根据图片url获取图片尺寸
- (CGSize)getImageSizeWithURL:(id)imageURL
{
    NSURL* URL = nil;
    if([imageURL isKindOfClass:[NSURL class]]){
        URL = imageURL;
    }
    if([imageURL isKindOfClass:[NSString class]]){
        URL = [NSURL URLWithString:imageURL];
    }
    if(URL == nil)
        return CGSizeZero;                  // url不正确返回CGSizeZero
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];
    NSString* pathExtendsion = [URL.pathExtension lowercaseString];
    
    CGSize size = CGSizeZero;
    if([pathExtendsion isEqualToString:@"png"]){
        size =  [self getPNGImageSizeWithRequest:request];
    }
    else if([pathExtendsion isEqual:@"gif"])
    {
        size =  [self getGIFImageSizeWithRequest:request];
    }
    else{
        size = [self getJPGImageSizeWithRequest:request];
    }
    if(CGSizeEqualToSize(CGSizeZero, size))                    // 如果获取文件头信息失败,发送异步请求请求原图
    {
        NSData* data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:URL] returningResponse:nil error:nil];
        UIImage* image = [UIImage imageWithData:data];
        if(image)
        {
            size = image.size;
        }
    }
    return size;
}
//  获取PNG图片的大小
- (CGSize)getPNGImageSizeWithRequest:(NSMutableURLRequest*)request
{
    [request setValue:@"bytes=16-23" forHTTPHeaderField:@"Range"];
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if(data.length == 8)
    {
        int w1 = 0, w2 = 0, w3 = 0, w4 = 0;
        [data getBytes:&w1 range:NSMakeRange(0, 1)];
        [data getBytes:&w2 range:NSMakeRange(1, 1)];
        [data getBytes:&w3 range:NSMakeRange(2, 1)];
        [data getBytes:&w4 range:NSMakeRange(3, 1)];
        int w = (w1 << 24) + (w2 << 16) + (w3 << 8) + w4;
        int h1 = 0, h2 = 0, h3 = 0, h4 = 0;
        [data getBytes:&h1 range:NSMakeRange(4, 1)];
        [data getBytes:&h2 range:NSMakeRange(5, 1)];
        [data getBytes:&h3 range:NSMakeRange(6, 1)];
        [data getBytes:&h4 range:NSMakeRange(7, 1)];
        int h = (h1 << 24) + (h2 << 16) + (h3 << 8) + h4;
        return CGSizeMake(w, h);
    }
    return CGSizeZero;
}
//  获取gif图片的大小
- (CGSize)getGIFImageSizeWithRequest:(NSMutableURLRequest*)request
{
    [request setValue:@"bytes=6-9" forHTTPHeaderField:@"Range"];
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if(data.length == 4)
    {
        short w1 = 0, w2 = 0;
        [data getBytes:&w1 range:NSMakeRange(0, 1)];
        [data getBytes:&w2 range:NSMakeRange(1, 1)];
        short w = w1 + (w2 << 8);
        short h1 = 0, h2 = 0;
        [data getBytes:&h1 range:NSMakeRange(2, 1)];
        [data getBytes:&h2 range:NSMakeRange(3, 1)];
        short h = h1 + (h2 << 8);
        return CGSizeMake(w, h);
    }
    return CGSizeZero;
}
//  获取jpg图片的大小
- (CGSize)getJPGImageSizeWithRequest:(NSMutableURLRequest*)request
{
    [request setValue:@"bytes=0-209" forHTTPHeaderField:@"Range"];
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    
    if ([data length] <= 0x58) {
        return CGSizeZero;
    }
    
    if ([data length] < 210) {// 肯定只有一个DQT字段
        short w1 = 0, w2 = 0;
        [data getBytes:&w1 range:NSMakeRange(0x60, 0x1)];
        [data getBytes:&w2 range:NSMakeRange(0x61, 0x1)];
        short w = (w1 << 8) + w2;
        short h1 = 0, h2 = 0;
        [data getBytes:&h1 range:NSMakeRange(0x5e, 0x1)];
        [data getBytes:&h2 range:NSMakeRange(0x5f, 0x1)];
        short h = (h1 << 8) + h2;
        return CGSizeMake(w, h);
    } else {
        short word = 0x0;
        [data getBytes:&word range:NSMakeRange(0x15, 0x1)];
        if (word == 0xdb) {
            [data getBytes:&word range:NSMakeRange(0x5a, 0x1)];
            if (word == 0xdb) {// 两个DQT字段
                short w1 = 0, w2 = 0;
                [data getBytes:&w1 range:NSMakeRange(0xa5, 0x1)];
                [data getBytes:&w2 range:NSMakeRange(0xa6, 0x1)];
                short w = (w1 << 8) + w2;
                short h1 = 0, h2 = 0;
                [data getBytes:&h1 range:NSMakeRange(0xa3, 0x1)];
                [data getBytes:&h2 range:NSMakeRange(0xa4, 0x1)];
                short h = (h1 << 8) + h2;
                return CGSizeMake(w, h);
            } else {// 一个DQT字段
                short w1 = 0, w2 = 0;
                [data getBytes:&w1 range:NSMakeRange(0x60, 0x1)];
                [data getBytes:&w2 range:NSMakeRange(0x61, 0x1)];
                short w = (w1 << 8) + w2;
                short h1 = 0, h2 = 0;
                [data getBytes:&h1 range:NSMakeRange(0x5e, 0x1)];
                [data getBytes:&h2 range:NSMakeRange(0x5f, 0x1)];
                short h = (h1 << 8) + h2;
                return CGSizeMake(w, h);
            }
        } else {
            return CGSizeZero;
        }
    }
}






@end
